package com.net.tool;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.ZipInputStream;

import org.xmlpull.v1.XmlPullParser;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.util.Xml;

public class DownloadPlugTooles extends BasicDownload {

	private boolean updateDownloadTable(String plugurl) {

		if (mDownloadState != DOWNLOAD_STATTE_DOWNLOADING) {
			return false;
		}
		Log.d("download", "适配文件下载开始 ");
		try {
			URL url = new URL(plugurl);
			mConnection = (HttpURLConnection) url.openConnection();
			InputStream inputStream = mConnection.getInputStream();
			BufferedInputStream bufferedInputStream = new BufferedInputStream(
					inputStream);

			OutputStream outputStream = mContext.openFileOutput(
					"SessionUrl.xml", Context.MODE_PRIVATE);

//			long length = mConnection.getContentLength();

//			long progress = 0;

			byte buffer[] = new byte[1024];
			int offset;
			while ((offset = bufferedInputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, offset);
//				progress += offset;
			}
			outputStream.flush();
			bufferedInputStream.close();
			inputStream.close();
			outputStream.close();
			mConnection.disconnect();

			Log.d("download", "适配文件下载结束 ");

			inputStream = mContext.openFileInput("SessionUrl.xml");
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(inputStream, "utf-8");

			for (int i = parser.getEventType(); i != XmlPullParser.END_DOCUMENT; i = parser
					.next()) {

				switch (i) {

				case XmlPullParser.START_TAG:
					Log.d("download", parser.getName());
					if (parser.getName().equals("SessionUrl")) {

						ContentValues contentValues = new ContentValues();

						for (int j = 0; j < parser.getAttributeCount(); j++) {
							contentValues.put(parser.getAttributeName(j),
									parser.getAttributeValue(j));

							Log.d("updateDownloadTable",
									parser.getAttributeName(j)
											+ parser.getAttributeValue(j));
						}
						contentValues.put(DownloadTable.PRIORITY, 10);

						Cursor cursor =

						getSqlite(mContext).query(
								DownloadTable.TB_NAME,
								new String[] { DownloadTable.TASKSTATE,
										DownloadTable.TASKTITLE,
										DownloadTable.TASKICON,
										DownloadTable.TASKSIZE },
								DownloadTable.TASKID + "=?",
								new String[] { contentValues
										.getAsString(DownloadTable.TASKID) },
								null, null, null);
						if (cursor.moveToFirst()) {
							contentValues.put(DownloadTable.TASKSTATE,
									cursor.getInt(0));
							contentValues.put(DownloadTable.TASKTITLE,
									cursor.getString(1));
							contentValues.put(DownloadTable.TASKICON,
									cursor.getString(2));
							contentValues.put(DownloadTable.TASKSIZE,
									cursor.getInt(3));

						}
						cursor.close();

						contentValues.put(DownloadTable.CLASS, getClass()
								.getName());
						getSqlite(mContext).replaceOrThrow(
								DownloadTable.TB_NAME, null, contentValues);
					}

				default:
					break;
				}
			}
			inputStream.close();

		} catch (Exception e) {

			Log.d("download", "适配文件下载取消 ");

			return false;
		}

		return true;

	}

	public DownloadPlugTooles(Context context) {
		super(context);
	}

	public DownloadPlugTooles(Context context, String taskId, String taskIcon,
			String title) {

		super(context);

		Log.d("DownloadPlugTooles", taskId + taskIcon + title);
		synchronized (BasicDownload.class) {

			mDownloadTaskId = taskId;
			mPriority = 10;
			Log.d("download", "mDownloadTaskId=" + mDownloadTaskId);

			Cursor cursor = getSqlite(context).query(DownloadTable.TB_NAME,
					new String[] { DownloadTable.TASKSTATE },
					DownloadTable.TASKID + "=?",
					new String[] { mDownloadTaskId }, null, null, null);

			if (cursor.moveToFirst()) {

				if (cursor.getInt(0) != DOWNLOAD_STATTE_DOWNLOADING) {
					updataTaskState(DOWNLOAD_STATE_PREPARE);
				}

				ContentValues initialValues = new ContentValues();
				initialValues.put(DownloadTable.TASKICON, taskIcon);
				initialValues.put(DownloadTable.TASKTITLE, title);
				getSqlite(mContext).update(DownloadTable.TB_NAME,
						initialValues, DownloadTable.TASKID + "=?",
						new String[] { mDownloadTaskId });
			} else {

				ContentValues initialValues = new ContentValues();
				initialValues.put(DownloadTable.CLASS, getClass().getName());
				initialValues.put(DownloadTable.PRIORITY, mPriority);
				initialValues.put(DownloadTable.TASKID, mDownloadTaskId);
				initialValues.put(DownloadTable.TASKICON, taskIcon);
				initialValues.put(DownloadTable.TASKTITLE, title);

				getSqlite(mContext).replaceOrThrow(DownloadTable.TB_NAME, null,
						initialValues);
				updataTaskState(DOWNLOAD_STATE_PREPARE);
			}

			cursor.close();

		}
	};

	public void downloading() {

		// 更新插件配置文件；

		Log.d("download", "获取服务器配置文件");

		String urls[] = ServerRootURLConfigure.getServerRootURLConfigure(
				mContext).getPlugsRootURLs();

		int state = dodownload();// 下载插件

		Log.d("download", "执行下载结果>> state=" + state);

		for (int i = 0; i < urls.length; i++) {

			Log.d("download", " dodownload url = " + i + " url=" + urls[i]
					+ " state=" + state + " mDownloadState=" + mDownloadState);

			if (state != 1 && (mDownloadState == DOWNLOAD_STATTE_DOWNLOADING)) {

				// updateListern(DOWNLOAD_STATE_PREPARE, mDownloadTaskId, 0, 1);

				if (ServerRootURLConfigure.getServerRootURLConfigure(mContext)
						.updateSeverConfigure()) {
					Log.d("download", "刷新服务器配置");
					i = 0;
					urls = ServerRootURLConfigure.getServerRootURLConfigure(
							mContext).getPlugsRootURLs();
				}

				if (updateDownloadTable(urls[i])) {
					Log.d("download", urls[i] + "更新成功");
					state = dodownload();
					Log.d("download", "重新下载结果=" + state);
				} else {
					// mFailedEx = DownloadListner.FAILED_EXTR_NET;
					break;
				}

			} else {
				break;
			}

		}

		if (mDownloadState == DOWNLOAD_STATTE_CANCAL) {
			updataTaskState(DOWNLOAD_STATTE_CANCAL);
			Log.d("download", "下载任务取消");

		} else if (mDownloadState == DOWNLOAD_STATE_PENDING) {
			updataTaskState(DOWNLOAD_STATE_PENDING);
			Log.d("download", "下载任务挂起");

		} else if (mDownloadState == DOWNLOAD_STATE_REMOVE) {
			updataTaskState(DOWNLOAD_STATE_REMOVE);
			Log.d("download", "下载任务删除");

		} else if (state != 1) {

			updataTaskState(DOWNLOAD_STATTE_FAILE, mFailedEx);
			Log.d("download", "下载任务失败" + mFailedEx);

		} else {
			updataTaskState(DOWNLOAD_STATTE_COMPLATAE);
			Log.d("download", "下载任务完成");
			openApkFile(new File(APK_ROOTP_PATH + (mDownloadTaskId + mServerVc)
					+ ".apk"));

		}

	}

	private int dodownload() {

		if (mDownloadState == DOWNLOAD_STATTE_CANCAL
				|| mDownloadState == DOWNLOAD_STATE_PENDING) {
			return 0;
		}

		Cursor cursor = getSqlite(mContext)
				.query(DownloadTable.TB_NAME,
						new String[] { DownloadTable.TASKURL,
								DownloadTable.SERVER_VC },
						DownloadTable.TASKID + "=?",
						new String[] { mDownloadTaskId }, null, null, null);

		if (cursor.moveToFirst()) {
			mServerVc = cursor.getInt(1);
			String url = cursor.getString(0);
			cursor.close();
			clearJunkfiles(mDownloadTaskId, mServerVc);
			mClintPath = APK_ROOTP_PATH + mDownloadTaskId + mServerVc + ".apk";

			if (download(mDownloadTaskId, url, mDownloadTaskId + mServerVc
					+ ".apk")) {

				try {
					@SuppressWarnings("resource")
					ZipInputStream zs = new ZipInputStream(new FileInputStream(
							mClintPath));
					zs.getNextEntry();
				} catch (Exception e) {
					return 0;
				}

				return 1;
			} else {
				return 0;
			}
		} else {
			return -1;
		}

	}

	public void cancal() {
		super.cancal();

		BgkTaskMange.getInstance().executeCommend(new AsyncCommend() {

			public void asyncCommend() {
				ServerRootURLConfigure.getServerRootURLConfigure(mContext)
						.cancalUpdateServerConfigure();
			}
		});

	}

}
